package com.app.globalexception;

/*
  @author 阿伟
  @create 2020-12-02:10:07
  全局异常处理器
*/

import com.common.entity.Code;
import com.common.entity.ResponseResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.security.sasl.AuthenticationException;
import java.util.Map;
import java.util.stream.Collectors;

//统一异常处理注解
@RestControllerAdvice
public class AppGlobalExceptionHandler {
    //用户异常处理
    @ExceptionHandler
    public ResponseResult userException(UserException u){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","用户模块发生异常"+u.getMessage());
    }
    //订单异常处理
    @ExceptionHandler
    public ResponseResult orderException(OrderException o){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","订单模块发生异常"+o.getMessage());
    }
    //聊一聊异常处理
    @ExceptionHandler
    public ResponseResult consultException(ConsultException c){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","聊一聊模块发生异常"+c.getMessage());
    }
    //反馈建议异常处理
    @ExceptionHandler
    public ResponseResult compliantException(CompliantException c){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","反馈建议发生异常"+c.getMessage());
    }
    //收藏异常处理
    @ExceptionHandler
    public ResponseResult collectException(CollectException c){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","收藏模块发生异常"+c.getMessage());
    }
    //用户认证异常处理
    @ExceptionHandler
    public ResponseResult authenticationException(AuthenticationException a){
        return ResponseResult.error(Code.RUN_Exception).Data("msg","用户认证模块发生异常"+a.getMessage());
    }

    //捕获全局运行时异常
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult appGlobalException(RuntimeException r){
        return ResponseResult.error(Code.RUN_Exception).Data("msg",r.getMessage());
    }

    //处理受查异常
    @ExceptionHandler
    public ResponseResult checkException(BindException b){
        //获取异常信息
        Map<String,String> info = b.getBindingResult()
                           .getFieldErrors()
                           .stream()
                           .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResponseResult.error(Code.CHECK_Exception).Data("msg",info);
    }


}
